import java.util.Stack;

public class Sort {
//快速排序的递归实现
    public static void swap2(int[] array,int child,int parent) {
        int tmp = array[child];
        array[child] = array[parent];
        array[parent] = tmp;
    }
    public static void quickSort(int[] array){
        // write code  here
        quick(array,0,array.length-1);

    }
    private static void quick(int[] array,int start,int end) {
        if(start >= end) return;
        //三数取中，使二叉树尽量均匀分布
        int index = midOfTree(array,start,end);
        swap2(array,index,start);

        int pivot = parttoin(array,start,end);
        quick(array,start,pivot-1);
        quick(array,pivot+1,end);

    }
    private static int midOfTree(int[] array,int left,int right) {
        int mid = (left + right) / 2;
        if(array[left] < array[right]) {
            if(array[mid] < array[left]) {
                return left;
            }else if(array[mid] > array[right]) {
                return right;
            }else {
                return mid;
            }
        }else {
            if(array[mid] > array[left]) {
                return left;
            }else if(array[mid] < array[right]) {
                return right;
            }else {
                return mid;
            }
         }
    }
    private static int parttoin(int[] array,int left,int right) {
        int key = array[left];
        while(left < right) {
            while(left < right && array[right] >= key) {
                right --;
            }
            //挖坑排序找基准
            array[left] = array[right];

            while (left < right && array[left] <= key) {
                left ++;
            }
            array[right] = array[left];

        }
        array[left] = key;
        return left;
    }



    //快速排序的非递归实现
    public static void quickSortNor(int[] array) {
        Stack<Integer> stack = new Stack<>();
        int left = 0;
        int right = array.length - 1;
        int pivot = parttoin(array,left,right);
        if(pivot - 1 > left) {
            stack.push(left);
            stack.push(pivot-1);
        }
        if(pivot + 1 < right) {
            stack.push(pivot+1);
            stack.push(right);
        }

        while(!stack.isEmpty()) {
            right = stack.pop();
            left = stack.pop();
            pivot = parttoin(array,left,right);
            if(pivot - 1 > left) {
                stack.push(left);
                stack.push(pivot-1);
            }
            if(pivot + 1 < right) {
                stack.push(pivot+1);
                stack.push(right);
            }
        }
    }
}
